package com.zlj.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.zlj.request.encoding.EncodingRequest;

/**
 * 设置GET请求和POST请求的编码问题
 */
@WebFilter(filterName = "/EncodingFilter",urlPatterns = "/*")
public class EncodingFilter implements Filter {

    public EncodingFilter() {
    }

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//处理POST请求编码问题
		request.setCharacterEncoding("utf-8");
		
		HttpServletRequest req = (HttpServletRequest)request;
		
		/*
		 * 掉包Request
		 * 写一个request的封装类，在放行时使用我们自己的request
		 * 
		 * 因为tomcat8以后，已经把get请求的编码方式由iso-8859-1设置为utf-8,所以再设置就会出现乱码
		 */
		if(req.getMethod().equalsIgnoreCase("get")) {
			EncodingRequest er = new EncodingRequest(req);
			chain.doFilter(er, response);
		} else {
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}
}
